<?php
class Default_Model_Users extends Zend_Db_Table{
	
	protected $_name = 'users';
	protected $_primary ='id';
	
	public function itemInSelectbox($arrParam = null, $options = null){
		$db = Zend_Registry::get('connectDb');
		//$db = Zend_Db::factory($adapter, $config);
		
		$quyen_nv = new Zendvn_System_Info();
		$quyen_nhom = $quyen_nv->getGroupInfo('permission');
		$quyen_info = $quyen_nv->getInfo();
		$quyen_member = $quyen_nv->getMemberInfo();
		$quyen_phongban = $quyen_nv->getPhongbanInfo();
		
		if($options['task'] == 'get-nhanvien'){
			$select = $db	->	select()
							->	from('users AS u',array('id','CONCAT(u.name," (",alias,")") AS name'))
							->	where('u.status = ?', 1)
							->	order('u.order ASC');
			
			if($quyen_nhom == 'Limit Access') {
				$select_category = $db 	-> select()
										-> from('phongban',array('id','name','parents'))
										-> where('status = ?',1);
				$resultCategory = $db	-> fetchAll($select_category);
				
				$system = new Zendvn_System_Recursive($resultCategory);
				$newArray = $system->builArray($quyen_phongban['id']);
				$tmp[] = $quyen_phongban['id'];
				if (count($newArray)>0) {
					foreach ($newArray as $key => $val) {
						$tmp[] = $val['id'];
					}
				}
				$ids = implode(',', $tmp);
				$select->where('u.id_phongban IN (' . $ids . ')');
				
				$result[0] = '- Lựa chọn -';
			}
			
			$result = $db	->	fetchPairs($select);
			ksort($result);
		}
		
		if($options['task'] == 'get-nhanvien-load'){
			
			if ($arrParam['id_phongban'] > 0) {
				$select = $db 	-> select()
								-> from('users AS u',array('id','CONCAT(u.name," (",alias,")") AS name'))
								-> where('u.status = ?', 1)
								-> order('u.order ASC');
				
				if($quyen_nhom == 'Limit Access') {
					$select_category = $db 	-> select()
											-> from('phongban',array('id','name','parents'))
											-> where('status = ?',1);
					$resultCategory = $db	-> fetchAll($select_category);
					
					$system = new Zendvn_System_Recursive($resultCategory);
					$newArray = $system->builArray($arrParam['id_phongban']);
					$tmp[] = $arrParam['id_phongban'];
					if (count($newArray)>0) {
						foreach ($newArray as $key => $val) {
							$tmp[] = $val['id'];
						}
					}
					$ids = implode(',', $tmp);
					if($ids != $quyen_phongban['id']) {
						$select->where('u.id_phongban IN (' . $ids . ')');
						$result = $db -> fetchPairs($select);
					}
					$result[$quyen_member['id']] = '- Tôi -';
				} else {
					$result = $db -> fetchPairs($select);
					$result[0] = '- Lựa chọn -';
				}
				
			} else {
				$result = array();
				$result[0] = '- Lựa chọn -';
			}
			asort($result);
		}
		
		return $result;
	}
	
	public function getItem($arrParam = null, $options = null){
		$db = Zend_Registry::get('connectDb');
		//$db = Zend_Db::factory($adapter, $config);
		if($options['task'] == 'admin-info' || $options['task'] == 'admin-edit'){
			$select = $db	-> select()
							-> from('users AS u',array('*',"DATE_FORMAT(u.visited_date,'%d/%m/%Y %H:%i:%s') AS visited_date","DATE_FORMAT(u.birthday,'%d/%m/%Y') AS birthday","DATE_FORMAT(u.date_star,'%d/%m/%Y') AS date_star","DATE_FORMAT(u.date_end,'%d/%m/%Y') AS date_end"))
							-> joinLeft('user_group AS g', 'u.group_id = g.id',array('group_name'))
							-> joinLeft('phongban AS pb', 'u.id_phongban = pb.id',array('name AS phongban_name'))
							-> joinLeft('chucvu AS cv', 'u.id_chucvu = cv.id',array('name AS chucvu_name'))
							-> joinLeft('coso AS cs', 'u.id_coso = cs.id',array('CONCAT(cs.name,": ",cs.diachi) AS coso_name'))
							-> where('u.id = ?', $arrParam['id']);
			$result = $db	->fetchRow($select);
		}
		return $result;
	}
	
	public function countItem($arrParam = null, $options = null){
		$db = Zend_Registry::get('connectDb');
		//$db = Zend_Db::factory($adapter, $config);
		$ssFilter  = $arrParam['ssFilter'];
		$select = $db->select()
		->from('users AS u', array('COUNT(u.id) AS totalItem'));
	
		if(!empty($ssFilter['keywords'])){
			$select->where("(u.user_name LIKE '%" . $ssFilter['keywords'] . "%') OR (u.id = '" . $ssFilter['keywords'] . "') OR (u.name LIKE '%" . $ssFilter['keywords'] . "%') OR (u.email LIKE '%" . $ssFilter['keywords'] . "%') OR (u.alias LIKE '%" . $ssFilter['keywords'] . "%')");
		}
		
		if($ssFilter['group_id']>0){
			$select->where('u.group_id = ?', $ssFilter['group_id']);
		}
		
		if($ssFilter['id_phongban'] > 0){
			$select_phongban = $db 	-> 	select()
			-> 	from('phongban',array('id','name','parents'))
			-> 	where('status = ?',1);
			$resultPhongban = $db	->	fetchAll($select_phongban);
		
			$system 	= new Zendvn_System_Recursive($resultPhongban);
			$newArray 	= $system->builArray($ssFilter['id_phongban']);
			$tmp[] 		= $ssFilter['id_phongban'];
			if (count($newArray)>0) {
				foreach ($newArray as $key => $val) {
					$tmp[] = $val['id'];
				}
			}
			$ids = implode(',', $tmp);
			$select->where('u.id_phongban IN (' . $ids . ')');
		}
	
		$result = $db->fetchOne($select);
		return $result;
	}
	
	public function listItem($arrParam = null, $options = null){
		$db = Zend_Registry::get('connectDb');
		//$db = Zend_Db::factory($adapter, $config);
		
		$paginator = $arrParam['paginator'];
		$ssFilter  = $arrParam['ssFilter'];
		
		$info 					= new Zendvn_System_Info();
		$user_id 				= $info->getMemberInfo('id');
	
		if($options['task'] == 'admin-list'){
			$select = $db	-> select()
							-> from('users AS u',array('*',"DATE_FORMAT(u.visited_date,'%d/%m/%Y %H:%i:%s') AS visited_date","DATE_FORMAT(u.birthday,'%d/%m/%Y') AS birthday","DATE_FORMAT(u.date_star,'%d/%m/%Y') AS date_star","DATE_FORMAT(u.date_end,'%d/%m/%Y') AS date_end"))
							-> joinLeft('user_group AS g', 'g.id = u.group_id','group_name')
							-> joinLeft('phongban AS pb', 'pb.id = u.id_phongban','pb.name AS phongban_name')
							-> joinLeft('chucvu AS cv', 'cv.id = u.id_chucvu','cv.name AS chucvu_name');
				
			if(!empty($ssFilter['col']) && !empty($ssFilter['order'])){
				$select->order($ssFilter['col'] . ' ' . $ssFilter['order']);
			}else{
				$select->order('u.id DESC');
			}
				
			if($paginator['itemCountPerPage'] > 0){
				$page = $paginator['currentPage'];
				$rowCount = $paginator['itemCountPerPage'];
				$select->limitPage($page, $rowCount);
			}
				
			if(!empty($ssFilter['keywords'])){
				$select->where("(u.user_name LIKE '%" . $ssFilter['keywords'] . "%') OR (u.id = '" . $ssFilter['keywords'] . "') OR (u.name LIKE '%" . $ssFilter['keywords'] . "%') OR (u.email LIKE '%" . $ssFilter['keywords'] . "%') OR (u.alias LIKE '%" . $ssFilter['keywords'] . "%')");
			}
			
			if($ssFilter['group_id'] > 0){
				$select->where('u.group_id = ?', $ssFilter['group_id']);
			}
			
			if($ssFilter['id_phongban'] > 0){
				$select_phongban = $db 	-> 	select()
										-> 	from('phongban',array('id','name','parents'))
										-> 	where('status = ?',1);
				$resultPhongban = $db	->	fetchAll($select_phongban);
				
				$system 	= new Zendvn_System_Recursive($resultPhongban);
				$newArray 	= $system->builArray($ssFilter['id_phongban']);
				$tmp[] 		= $ssFilter['id_phongban'];
				if (count($newArray)>0) {
					foreach ($newArray as $key => $val) {
						$tmp[] = $val['id'];
					}
				}
				$ids = implode(',', $tmp);
				$select->where('u.id_phongban IN (' . $ids . ')');
			}
			
			$result = $db->fetchAll($select);
		}
		
		if($options['task'] == 'user-all'){
			$select = $db	-> select()
							-> from('users AS u',array('*',"DATE_FORMAT(u.visited_date,'%d/%m/%Y %H:%i:%s') AS visited_date","DATE_FORMAT(u.birthday,'%d/%m/%Y') AS birthday"))
							-> joinLeft('user_group AS g', 'g.id = u.group_id','group_name')
							-> joinLeft('phongban AS pb', 'pb.id = u.id_phongban','pb.name AS phongban_name')
							-> joinLeft('chucvu AS cv', 'cv.id = u.id_chucvu','cv.name AS chucvu_name');
			$result = $db	-> fetchAssoc($select);
		}
	
		return $result;
	}
	
	public function saveItem($arrParam = null, $options = null){
	
		if($options['task'] == 'admin-add'){
			$info 				= new Zendvn_System_Info();
			$created_by 		= $info->getMemberInfo('id');
			
			$row 				= $this->fetchNew();
			$encode 			= new Zendvn_Encode();
			
			$birthday 			= '0000-00-00';
			if(!empty($arrParam['birthday'])) {
				$date 				= new Zend_Date();
				$date->set($arrParam['birthday']);
				$birthday 			= $date->toString('YYYY-MM-dd');
			}
			$date_star 			= '0000-00-00';
			if(!empty($arrParam['date_star'])) {
				$date 				= new Zend_Date();
				$date->set($arrParam['date_star']);
				$date_star 			= $date->toString('YYYY-MM-dd');
			}
			$date_end 			= '0000-00-00';
			if(!empty($arrParam['date_end'])) {
				$date 				= new Zend_Date();
				$date->set($arrParam['date_end']);
				$date_end 			= $date->toString('YYYY-MM-dd');
			}
				
			$row->user_name 	= stripslashes($arrParam['user_name']);
			$row->password 		= $encode->password($arrParam['password']);
			$row->email 		= $arrParam['email'];
			$row->group_id 		= $arrParam['group_id'];
			$row->name 			= $arrParam['name'];
			$row->mobile 		= $arrParam['mobile'];
			$row->alias		 	= $arrParam['alias'];
			$row->birthday 		= $birthday;
			$row->date_star 	= $date_star;
			$row->date_end 		= $date_end;
			$row->status 		= $arrParam['status'];
			$row->content		= stripslashes($arrParam['content']);
			$row->created 		= @date("Y-m-d H:i:s");
			$row->created_by	= $created_by;
			$row->user_avatar 	= $arrParam['user_avatar'];
			$row->id_chucvu 	= $arrParam['id_chucvu'];
			$row->id_phongban 	= $arrParam['id_phongban'];
			$row->id_coso	 	= $arrParam['id_coso'];
			
			$lastId = $row->save();

			$tblLogs = new Default_Model_Logs();
			$arrLogs = array(
					'id_user' 	=> $arrParam['adminInfo']['id'],
					'name'		=> 'Thêm nhân viên mới mới - id ' . $lastId,
					'date'		=> @date('U')
			);
			$tblLogs->saveItem($arrLogs, array('task' => 'admin-add'));
		}
	
		if($options['task'] == 'admin-edit'){
			
			$where 				= ' id=' . $arrParam['id'];
			$row 				= $this->fetchRow($where);
			
			$info 				= new Zendvn_System_Info();
			$modified_by 		= $info->getMemberInfo('id');
			
			$birthday 			= '0000-00-00';
			if(!empty($arrParam['birthday'])) {
				$date 				= new Zend_Date();
				$date->set($arrParam['birthday']);
				$birthday 			= $date->toString('YYYY-MM-dd');
			}
			
			
			$date_star 			= '0000-00-00';
			if(!empty($arrParam['date_star'])) {
				$date 				= new Zend_Date();
				$date->set($arrParam['date_star']);
				$date_star 			= $date->toString('YYYY-MM-dd');
			}
			$date_end 			= '0000-00-00';
			if(!empty($arrParam['date_end'])) {
				$date 				= new Zend_Date();
				$date->set($arrParam['date_end']);
				$date_end 			= $date->toString('YYYY-MM-dd');
			}
			
			$encode = new Zendvn_Encode();
			$row->user_name 	= stripslashes($arrParam['user_name']);
			if(!empty($arrParam['password'])){
				$row->password 	= $encode->password($arrParam['password']);
			}
			$row->email 		= $arrParam['email'];
			$row->group_id 		= $arrParam['group_id'];
			$row->name 			= $arrParam['name'];
			$row->mobile 		= $arrParam['mobile'];
			$row->alias 		= $arrParam['alias'];
			$row->birthday 		= $birthday;
			$row->date_star 	= $date_star;
			$row->date_end 		= $date_end;
			$row->status 		= $arrParam['status'];
			$row->content		= stripslashes($arrParam['content']);
			$row->modified 		= @date("Y-m-d H:i:s");
			$row->modified_by	= $modified_by;
			$row->user_avatar 	= $arrParam['user_avatar'];
			$row->id_chucvu 	= $arrParam['id_chucvu'];
			$row->id_phongban 	= $arrParam['id_phongban'];
			$row->id_coso	 	= $arrParam['id_coso'];
			
			$row->save();

			$lastId				= $arrParam['id'];
			
			$tblLogs = new Default_Model_Logs();
			$arrLogs = array(
					'id_user' 	=> $arrParam['adminInfo']['id'],
					'name'		=> 'Sửa nhân viên - id ' . $arrParam['id'],
					'date'		=> @date('U')
			);
			$tblLogs->saveItem($arrLogs, array('task' => 'admin-add'));
		}
		
		if($options['task'] == 'admin-password'){
				
			$where 				= ' id=' . $arrParam['id'];
			$row 				= $this->fetchRow($where);
				
			$encode				= new Zendvn_Encode();
			$row->password 		= $encode->password($arrParam['password_new']);
				
			$row->save();
			
			$lastId				= $arrParam['id'];
			
			$tblLogs = new Default_Model_Logs();
			$arrLogs = array(
					'id_user' 	=> $arrParam['adminInfo']['id'],
					'name'		=> 'Đổi mật khẩu: ' . $arrParam['password_new'],
					'date'		=> @date('U')
			);
			$tblLogs->saveItem($arrLogs, array('task' => 'admin-add'));
		}
		
		if($options['task'] == 'admin-visited'){
		
			$where 				= " user_name = '" . $arrParam['user_name'] . "'";
			$row 				= $this->fetchRow($where);

			$row->visited_date 	= @date("Y-m-d H:i:s");
			$row->visited_ip 	= $_SERVER['REMOTE_ADDR'];
		
			$row->save();
			
			$lastId				= $arrParam['id'];
		}
		
		return $lastId;
	}
	
	public function deleteItem($arrParam = null, $options = null){
		if($options['task'] == 'admin-delete'){
			
			//------------- LAY TEN HINH ANH user_avatar -----------//
			$row = $this->getItem($arrParam, array('task'=>'delete'));
			
			//------------- XOA user_avatar -----------------------//
			$upload_dir = FILE_PATH . '/users';
			$upload = new Zendvn_File_Upload();
			$upload->removeFile($upload_dir . '/orignal/' . $row['user_avatar']);
			$upload->removeFile($upload_dir . '/img100x100/' . $row['user_avatar']);
			$upload->removeFile($upload_dir . '/img450x450/' . $row['user_avatar']);
			
			$where = ' id=' . $arrParam['id'];
			$result = $this->delete($where);
			
			$tblLogs = new Default_Model_Logs();
			$arrLogs = array(
					'id_user' 	=> $arrParam['adminInfo']['id'],
					'name'		=> 'Xóa nhân viên - id ' . $arrParam['id'],
					'date'		=> @date('U')
			);
			$tblLogs->saveItem($arrLogs, array('task' => 'admin-add'));
		}
	
		if($options['task'] == 'admin-delete-muti'){
			$cid = explode(',', $arrParam['cid']);
			if(!empty($cid) && isset($arrParam['cid'])){
				foreach ($cid as $key){
					$arrParam['id'] = $key;
					
					//------------- LAY TEN HINH ANH user_avatar -----------//
					$row = $this->getItem($arrParam, array('task'=>'delete'));
					
					//------------- XOA user_avatar -----------------------//
					$upload_dir = FILE_PATH . '/users';
					$upload = new Zendvn_File_Upload();
					$upload->removeFile($upload_dir . '/orignal/' . $row['user_avatar']);
					$upload->removeFile($upload_dir . '/img100x100/' . $row['user_avatar']);
					$upload->removeFile($upload_dir . '/img450x450/' . $row['user_avatar']);

				}
				$ids = implode(',', $cid);
				$where = 'id IN (' . $ids . ')';
				$this->delete($where);
				
				$tblLogs = new Default_Model_Logs();
				$arrLogs = array(
						'id_user' 	=> $arrParam['adminInfo']['id'],
						'name'		=> 'Xóa nhân viên - id ' . $ids,
						'date'		=> @date('U')
				);
				$tblLogs->saveItem($arrLogs, array('task' => 'admin-add'));
			}
				
		}
	}
	
	public function changeStatus($arrParam = null, $options = null){
		$cid = $arrParam['cid'];
		if(count($cid) > 0){
			if($arrParam['type'] == 1){
				$status = 1;
			}else{
				$status = 0;
			}
				
			$id = implode(',', $cid);
			$data = array('status' => $status);
			$where = 'id IN (' . $id . ')';
			$this->update($data, $where);
			
			$tblLogs = new Default_Model_Logs();
			$arrLogs = array(
					'id_user' 	=> $arrParam['adminInfo']['id'],
					'name'		=> 'Thay đổi trạng thái nhân viên - id ' . $id,
					'date'		=> @date('U')
			);
			$tblLogs->saveItem($arrLogs, array('task' => 'admin-add'));
		}
		if($arrParam['id'] > 0){
			if($arrParam['type'] == 1){
				$status = 1;
			}else{
				$status = 0;
			}
			$data = array('status' => $status);
			$where = 'id = ' . $arrParam['id'];
			$this->update($data, $where);
			
			$tblLogs = new Default_Model_Logs();
			$arrLogs = array(
					'id_user' 	=> $arrParam['adminInfo']['id'],
					'name'		=> 'Thay đổi trạng thái nhân viên - id ' . $arrParam['id'],
					'date'		=> @date('U')
			);
			$tblLogs->saveItem($arrLogs, array('task' => 'admin-add'));
		}
	}
}